const exApp = require('../index.js')
const express = require('express');
const router = express.Router();
const mysql = require("../connect/pomsql")
const { resHandler } = require('../model/resHandler')
router.get('/mines', async (req, res, next) => {
    let sql = `select * from users`;
    let result = await mysql(sql)
    resHandler(res,result,'操作失败')
})
// 粉丝关注修改
router.post('/editData', async function (req, res) {
    let {fans,id}=req.body
    id=id*1
    let sql = `update users set fans='${fans}' where id = '${id}'`
    let data = await mysql(sql)
    resHandler(res,data,'操作失败')
})
// 确认收货修改
router.post('/editGoods', async function (req, res) {
    let {bought,id}=req.body
    id=id*1
    let sql = `update users set bought='${bought}' where id = '${id}'`
    let data = await mysql(sql)
    resHandler(res,data,'操作失败')
})
// 修改密码
// 加密
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;
const salt = bcrypt.genSaltSync(SALT_WORK_FACTOR);
// 密码解密
let compare = (myPlaintextPassword, hash) => {
    return new Promise((resolve, reject) => {
      bcrypt.compare(myPlaintextPassword, hash, (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    });
  };
router.post('/editPassword', async function (req, res) {
    let {beforePassword,password,email}=req.body
    let user = `SELECT * from users where email = '${email}'`;
    let data2=await mysql(user)
    var isTrue = await compare(beforePassword, data2[0].password);
    if(isTrue){
        var hash = bcrypt.hashSync(password, salt);
        password = hash;
        let sql = `update users set password='${password}' where email = '${email}'`
        let data = await mysql(sql)
        resHandler(res,data,'操作失败')
    }else{
        res.json({code:500,msg:'密码错误',icon:'fail'})
    }
})
// 修改用户名
router.post('/editNames', async function (req, res) {
    let {name,email}=req.body
    let sql = `update users set name='${name}' where email = '${email}'`
    let data = await mysql(sql)
    resHandler(res,data,'操作失败')
})
exApp.use('/', router);